package org.ls.wxscancodes.util;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;

public class httputil {
    private static final Logger logger = LoggerFactory.getLogger(httputil.class);
    private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
    private static RequestConfig requestConfig;

    public httputil() {
    }

    /**
     * 情况方法直接放这里就行
     */


    static {
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
        Builder configBuilder = RequestConfig.custom();
        configBuilder.setConnectTimeout(60000);
        configBuilder.setSocketTimeout(70000);
        configBuilder.setConnectionRequestTimeout(30000);
        requestConfig = configBuilder.build();
    }
    /**
     * Post方式
     * @param apiUrl
     * @param json json数据
     * @param headerMap 请求头
     * @return
     */
    public static String doPost(String apiUrl, String json, Map<String,String> headerMap) {
        long start = System.currentTimeMillis();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        int statusCode = -999;

        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            //循环增加header
            if (headerMap != null) {
                Iterator headerIterator = headerMap.entrySet().iterator();
                while(headerIterator.hasNext()){
                    Entry<String,String> elem = (Entry<String, String>) headerIterator.next();
                    httpPost.addHeader(elem.getKey(),elem.getValue());
                }
            }
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            statusCode = response.getStatusLine().getStatusCode();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception var20) {
            logger.info("HttpUtil post error:" + var20.getMessage());
            var20.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException var19) {
                    var19.printStackTrace();
                }
            }

            logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start});
        }

        return httpStr;
    }

    /**
     * Post请求
     * @param apiUrl 请求链接
     * @param params 请求类型：x-www-form-urlencoded
     * @return
     */
    public static String doPost(String apiUrl, Map<String, Object> params) {
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        String httpStr = null;
        int statusCode = -999;
        //创建http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpPost实例
        HttpPost httpPost = new HttpPost(apiUrl);
        try {
            httpPost.setConfig(requestConfig);
            List<NameValuePair> pairList = new ArrayList();
            Iterator i$ = params.entrySet().iterator();

            while(i$.hasNext()) {
                Entry<String, Object> entry = (Entry)i$.next();
                NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
                pairList.add(pair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            logger.info("HttpUtil发生错误:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            logger.info("request path:{}, param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, params.toString(), statusCode, httpStr, System.currentTimeMillis() - start});
        }

        return httpStr;
    }


    /**
     * @param url
     * @param params 带参数
     * @return
     */
    public static String doGet(String url, Map<String, Object> params) {
        long start = System.currentTimeMillis();
        StringBuffer param = new StringBuffer();
        int i = 0;
        for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
            String key = (String)i$.next();
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }

            param.append(key).append("=").append(params.get(key));
        }
        String apiUrl = url + param;
        String result = null;
        //创建一个httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        int statusCode = -999;
        try {
            HttpGet httpGet = new HttpGet(apiUrl);
            HttpResponse response = httpClient.execute(httpGet);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (Exception var18) {
            logger.info("httputil get error:" + var18.getMessage());
            var18.printStackTrace();
        } finally {
            if (httpClient != null) {
                //关闭流
                HttpClientUtils.closeQuietly(httpClient);
            }

            logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start});
        }

        return result;
    }



}
